# coding=utf-8
from elasticsearch import Elasticsearch
from valutil   import *

class TiES:
    def __init__(self):
        self.host='47.92.139.146'
        self.port='9200'
        self.index="shiji21_index";
        self.titype="shiji_ti";
        self.papertype='shiji_paper'

        self.es = Elasticsearch(hosts=[self.host + ":" + self.port], timeout=5000)

    def searchPaper(self,keyword='',channel='',grade='',paperyear='',paperarea='',papertype='',pageno=1,pagesize=10):
        body = {}
        query = {};
        filter = []
        start = (pageno - 1) * pagesize;
        bool = {}
        must = {}
        body["from"] = start;
        body["size"] = pagesize;
        if (not isBlank(channel)):
            filter.append({"channel": channel});
        if (not isBlank(grade)):
            filter.append({"grade": grade});
        if (not isBlank(paperyear)):
            filter.append({"paperyear": paperyear});
        if (not isBlank(paperarea)):
            filter.append({"paperarea": paperyear});
        if (not isBlank(papertype)):
            filter.append({"papertype"}, papertype);

        if (len(filter) != 0):
            bool["filter"] = filter;
        if (not isBlank(keyword)):
            must["match"] = {'papername': keyword}
            bool['must'] = must;
        if (len(bool) > 0):
            query["bool"] = bool;
            body['query'] = query;
        res = self.es.search(index=self.index, doc_type=self.papertype, body=body)
        return res;


    def searchTi(self,keyword='',channel='',grade='',paperyear='',paperarea='', papertype='',pageno=1,pagesize=10):
        body={}
        query={};
        filter=[]
        start=(pageno-1)*pagesize;
        bool={}
        must={}
        body["from"]=start;
        body["size"]=pagesize;
        if(not isBlank(channel)):
            filter.append({"channel":channel});
        if(not isBlank(grade)):
            filter.append({"grade": grade});
        if(not isBlank(paperyear)):
            filter.append({"paperyear": paperyear});
        if(not isBlank(paperarea)):
            filter.append({"paperarea": paperyear});
        if(not isBlank(papertype)):
            filter.append({"papertype"},papertype);

        if(len(filter)!=0):
            bool["filter"]=filter;
        if(not isBlank(keyword)):
            must["match"]={'tquestion':keyword}
            bool['must']=must;
        if(len(bool)>0):
            query["bool"]=bool;
            body['query']=query;
        res=self.es.search(index=self.index,doc_type=self.titype,body=body)
        return res;

#es=TiES();
#vs=es.searchTiByKeyWord('sdfsfsfsdf',1,10);
#a=1;